package com.rjh.concurrent.create;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j(topic = "c.InterruptedTest")
public class InterruptedTest {

    public static void main(String[] args) throws InterruptedException {

        /**
         * 打断 sleep，wait，join 的线程
         */
//        Thread t2 = new Thread() {
//            @Override
//            public void run() {
//                log.debug("线程任务执行");
//                try {
//                    Thread.sleep(10000); // wait, join
//                } catch (InterruptedException e) {
//                    //e.printStackTrace();
//                    log.debug("被打断");
//
//                    System.out.println("t2:"+Thread.currentThread().isInterrupted());
//                }
//            }
//        };
//        t2.start();
//        Thread.sleep(500);
//        log.debug("111是否被打断？{}",t2.isInterrupted());
//        t2.interrupt();
//        log.debug("222是否被打断？{}",t2.isInterrupted());
//        Thread.sleep(500);
//        log.debug("222是否被打断？{}",t2.isInterrupted());
//        log.debug("主线程");

        /**
         * 打断正常运行的线程
         */
        Thread t2 = new Thread(() -> {
            while(true) {
                boolean interrupted = Thread.currentThread().isInterrupted();
                if(interrupted) {
                    log.debug("被打断了, 退出循环");
                    break;
                }
            }
        }, "t2");
        t2.start();
        Thread.sleep(1000);
        log.debug("interrupt");
        t2.interrupt();


//        Thread thread = new Thread(()->{
//            while (true){
//                if (Thread.currentThread().isInterrupted()){
//                    log.debug("线程被打断。。。{}",Thread.currentThread().isInterrupted());
//                    break;
//                }
//                try {
//                    TimeUnit.SECONDS.sleep(1);
//                    log.debug("runing isInterrupted : {}",Thread.currentThread().isInterrupted());
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                    log.debug("exception isInterrupted : {}",Thread.currentThread().isInterrupted());
////                    Thread.currentThread().interrupt();
//                }
//            }
//        });
//
//        thread.start();
//        TimeUnit.SECONDS.sleep(5);
//        thread.interrupt();
//
//        log.debug("{}",thread.isInterrupted());
    }
}
